<template>
  <el-dialog
    :model-value="modelValue"
    :title="$t('msg.excel.roleDialogTitle')"
    @close="closed"
  >
    <el-tree
      ref="treeRef"
      :data="allPermission"
      show-checkbox
      check-strictly
      node-key="id"
      default-expand-all
      :props="defaultProps"
    >
    </el-tree>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.universal.cancel') }}</el-button>
        <el-button type="primary" @click="onConfirm">{{
          $t('msg.universal.confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
import { permissionList } from '@/api/permission'
import { watchSwitchLang } from '@/utils/i18n'
import { rolePermission } from '@/api/role'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  roleId: {
    type: String,
    required: true
  }
})

const emits = defineEmits(['update:modelValue'])
const defaultProps = {
  children: 'children',
  label: 'permissionName'
}
// 全部权限
const allPermission = ref([])
const getAllPermissionList = async () => {
  allPermission.value = await permissionList()
}
getAllPermissionList()
watchSwitchLang(getAllPermissionList)

const treeRef = ref(null)
// 获取当前角色权限
const getRolePermission = async () => {
  const checkedKeys = await rolePermission(props.roleId)
  treeRef.value.setCheckedKeys(checkedKeys)
}
watch(
  () => props.roleId,
  (val) => {
    if (val) {
      getRolePermission()
    }
  }
)

// 取消
const closed = () => {
  emits('update:modelValue', false)
}

// 点击确认
const i18n = useI18n()
const onConfirm = () => {
  // TODO 调接口更新权限
  console.log(treeRef.value.getCheckedKeys())
  ElMessage.success(i18n.t('msg.role.updateRoleSuccess'))
  closed()
}
</script>

<style lang="scss" scoped>
</style>
